import { ref, unref } from 'vue'
import type { FormSchemaItem } from '../types/form'
/*
 * @Author: C.
 * @Date: 2023-12-12 14:30:09
 */
type IProps = {
  schemas: FormSchemaItem[]
}
interface IAction {
  validate: () => Promise<Recordable>
  reset: () => void
  setFieldsValue: (model: Recordable) => void
  getFieldsValue: () => Recordable
}
export function useForm(
  props?: IProps
): [register: (obj: Recordable) => void, action: IAction] {
  const actionRef = ref<Recordable>({})
  function register(action: any) {
    if (action.type == 'mounted') {
      //
      actionRef.value = action
      action.setProps({
        ...unref(props),
      })
    }
    // actionRef.value=action
  }
  const Action: IAction = {
    // 提交
    validate: async () => {
      const res = await unref(actionRef).validate()
      return res
    },
    reset: () => {
      unref(actionRef).reset()
    },
    setFieldsValue: (model: Recordable) => {
      unref(actionRef).setFieldsValue(model)
    },
    getFieldsValue: () => {
      return unref(actionRef).getFieldsValue()
    },
  }
  return [register, Action]
}
